package com.lepu.app.fun.chat.core;

import java.io.File;

import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.app.application.MyApplication;
import com.app.utils.LoginUtil;
import com.app.utils.SdLocal;
import com.app.utils.Setting;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.secure.EncodeMD5;
import com.lepu.app.fun.chat.bean.ChatError;
import com.lepu.app.fun.chat.bean.Media;
import com.lepu.app.fun.chat.bean.ResultData;
import com.lepu.app.fun.chat.util.Constants;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

/**
 * 
 * @author wxd
 *
 */
public class MediaManager {

	private static MediaManager mInstance = null;
	
    private MediaListener mediaListener;

    public interface MediaListener {
        void onUpload(Media media);

        void onDownload(Media media);

        void onMediaError(long sessionId, String messageId, Media media, ChatError chatError);
    }

    private MediaManager()
    {
    	this.mediaListener = ChatManager.getInstance();
    }
    
    public static MediaManager getInstance() {
        if(mInstance == null)
        {
        	mInstance = new MediaManager();
        }
        return mInstance;
    }

    //===================================================
    public void upload(Media media) {
        try {
            uploadFile(media);
        } catch (Exception e) {
            mediaListener.onMediaError(media.getSessionId(), media.getMessageId(), media,
                    MessageBuilder.buildError(Constants.Error.MEDIA_UPLOAD_ERROR, e));
        }
    }

    public void download(final Media media) {

        String downloadUrl = "";
        String fileName = "";
        String filePath = "";

        if (media.getMessageType() == Constants.Chat.CHAT_MESSAGE_TYPE_IMAGE) {
            downloadUrl = media.getThumbnailImageId();
            fileName = EncodeMD5.getMd5(downloadUrl);
            filePath = SdLocal.getChatImagePath(MyApplication.getInstance(),LoginUtil.getUserId(),fileName);
        } else if (media.getMessageType() == Constants.Chat.CHAT_MESSAGE_TYPE_AUDIO) {
            downloadUrl = media.getObjectId();
            fileName = EncodeMD5.getMd5(downloadUrl);
            filePath = SdLocal.getChatVoicePath(MyApplication.getInstance(), LoginUtil.getUserId(), fileName);
        }

        final String tempDownloadUrl = downloadUrl;
        HttpUtils http = new HttpUtils();
        http.download(downloadUrl, filePath
                , true, true, new RequestCallBack<File>() {
            public void onStart() {

            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                Log.i("", current + "/" + total);
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Log.i("", msg);
                mediaListener.onDownload(media);
            }

            @Override
            public void onSuccess(ResponseInfo<File> responseInfo) {
                String path = responseInfo.result.getPath();
                media.setFileName(path);
                media.setFullName(path);
                media.setObjectId(tempDownloadUrl);

                mediaListener.onDownload(media);
            }
        });
    }

    public ResultData uploadFile(final Media media) throws Exception {
        LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
        JSONObject params = new JSONObject();
        params.put("DeviceID", String.valueOf(Setting.DEVICEID));
        params.put("ApplicationID", Setting.APPLICATIONID);
        params.put("UserID", loginInfo.UserID);
        params.put("LoginToken", loginInfo.LoginToken);
        final RequestParams requestParams = new RequestParams();
        if (media.getMimeType().contains("image")) {
            params.put("MimeType", 1);
            LogUtilBase.LogD(" mediamanager  send Photo url:", media.getFullName());
            requestParams.addBodyParameter("File", new File(media.getFullName()));
        } else if (media.getMimeType().contains("audio")) {
            params.put("MimeType", 2);
            requestParams.addBodyParameter("File", new File(media.getFullName()));
        }else if (media.getMimeType().contains("video")) {
            params.put("MimeType", 3);
            requestParams.addBodyParameter("File", new File(media.getFullName()));
        }
        //-------------------------------------------------
        requestParams.addBodyParameter("ht", params.toString());
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.POST, Setting.getUploadFileURL(), requestParams, new RequestCallBack<Object>() {
            @Override
            public void onSuccess(ResponseInfo<Object> responseInfo) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject((String) responseInfo.result);
                    String state = jsonObject.optJSONObject("Result").optString("Status");
                    if (!state.equals("200"))
                    {
                        mediaListener.onMediaError(media.getSessionId(), media.getMessageId(), media,
                                MessageBuilder.buildError(Constants.Error.MEDIA_UPLOAD_ERROR, "state==>>"+state));
                        return;
                    }

                    String objectId = jsonObject.optJSONObject("Result").optJSONObject("DetailInfo").optString("FileUrl");

                    if (media.getMimeType().contains("image")) {

                        String thum = "";
                        String[] sourceStrArray = objectId.split("\\.");
                        if (sourceStrArray != null && sourceStrArray.length > 1) {
                            String str[] = objectId.split("\\." + sourceStrArray[sourceStrArray.length - 1]);
                            if (str[0] != null) {
                                thum = str[0] + "_W_200_V." + sourceStrArray[sourceStrArray.length - 1];
                            }
                        }
                        media.setThumbnailImageId(thum);
                    }
                    media.setObjectId(objectId);
                    media.setLargeImageId(objectId);

                    mediaListener.onUpload(media);
                } catch (JSONException e) {
                    e.printStackTrace();

                    mediaListener.onMediaError(media.getSessionId(), media.getMessageId(), media,
                            MessageBuilder.buildError(Constants.Error.MEDIA_UPLOAD_ERROR, e));
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                LogUtilBase.LogD(null,"mediaManager update is error"+ s);

                mediaListener.onMediaError(media.getSessionId(), media.getMessageId(), media,
                        MessageBuilder.buildError(Constants.Error.MEDIA_UPLOAD_ERROR, e));
            }
        });
        return null;
    }

}

